#!/bin/bash
#docker-24.0.9.tgz
script_path=$(cd "$(dirname "$0")" && pwd)
docker_version=24.0.9
arch_type=$(uname -m)
docker_url=https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/static/stable/${arch_type}

[ -n "$1" ] && docker_version="$1"
docker_download() {
  #  curl -o /opt/software/ $URL
  curl -O "${docker_url}"/docker-"${docker_version}".tgz
}

docker_install() {
  tar xf docker-"${docker_version}".tgz -C /usr/bin/ --strip-components=1
  # 发现docker有自己的用户和组不友好，系统默认 bin 目录都是root用户，但组可能有其他的
  find /usr/bin/ -type f -not -user root -exec chown root:root {} \;

  cat >/etc/systemd/system/docker.service <<"EOF"
[Unit]
Description=Docker Application Container Engine
Documentation=https://docs.docker.com
After=network-online.target firewalld.service
Wants=network-online.target

[Service]
Type=notify
ExecStart=/usr/bin/dockerd
ExecReload=/bin/kill -s HUP \$MAINPID
LimitNOFILE=infinity
LimitNPROC=infinity
TimeoutStartSec=0
Delegate=yes
KillMode=process
Restart=on-failure
StartLimitBurst=3
StartLimitInterval=60s

[Install]
WantedBy=multi-user.target
EOF
}
docker_config() {
  [ -d /etc/docker ] || mkdir -p /etc/docker
  cat >/etc/docker/daemon.json <<"EOF"
{
  "exec-opts": [
    "native.cgroupdriver=systemd"
  ],
  "registry-mirrors": [
    "https://docker.nju.edu.cn/",
    "https://docker.mirrors.ustc.edu.cn/",
    "https://kuamavit.mirror.aliyuncs.com"
  ],
  "max-concurrent-downloads": 10,
  "log-driver": "json-file",
  "log-level": "warn",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
  },
  "data-root": "/var/lib/docker"
}
EOF
}

install_iptables() {
  if command -v apt >/dev/null; then
    apt install -y iptables
  elif command -v yum >/dev/null; then
    yum install -y iptables
  else
    echo "Unknown release, please install Iptabol manually"
  fi
}

main() {
  [ -f ${script_path}/docker-"${docker_version}".tgz ] || docker_download
  docker_install
  docker_config
  grep docker /etc/group >/dev/null || groupadd docker
  command -v iptables >/dev/null || install_iptables
  systemctl enable --now docker
  #  systemctl is-active docker >>/dev/null &&  echo "docker running" || echo "docker failed,please check!!!"
  if [ $(systemctl is-active docker) == "active" ]; then
    echo "docker is running,deleting docker archive"
    rm -rf ${script_path}/docker-"${docker_version}".tgz
  else
    echo "docker failed,please check!!!"
  fi
}
main
